package hn.cch.redis.repository;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import hn.cch.mysql.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author CCH
 * @version 2018.08.29
 */

@Repository
public class UserRepository {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 存一个用户
     * @param key
     * @param user
     * @param timeout
     */
    public void setUser(String key, User user, Long timeout){

        Gson gson = new Gson();
        String value  = gson.toJson(user);
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.MINUTES);
    }

    /**
     * 存多个用户
     * @param key
     * @param users
     * @param timeout
     */
    public void setUsers(String key, List<User> users, Long timeout){

        Gson gson = new Gson();
        String value  = gson.toJson(users);
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.MINUTES);
    }

    /**
     * 取一个用户
     * @param key
     * @return
     */
    public User getUser(String key){

        User user = null;
        String json = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(json)){
            Gson gson = new Gson();
            user = gson.fromJson(json, User.class);
        }
        return user;
    }

    /**
     * 取多个用户
     * @param key
     * @return
     */
    public List<User> getUsers(String key){

        List<User> users = null;
        String json = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(json)){
            Gson gson = new Gson();
            users = gson.fromJson(json, new TypeToken<List<User>>(){}.getType());
        }
        return users;
    }

    /**
     * 删除
     * @param key
     */
    public void del(String key){
        redisTemplate.opsForValue().getOperations().delete(key);
    }



}
